/*
 * @Author: DUST
 * @Date: 2023-05-26 16:29:23
 * @LastEditors: DUST
 * @LastEditTime: 2023-05-29 13:40:34
 * @FilePath: \koa-node-ts\utils\auth.ts
 * @Description:
 * undefined
 */

import jwt, { JsonWebTokenError, JwtPayload, TokenExpiredError } from "jsonwebtoken";
import config from "../app/config";

function sign(data: any) {
  return jwt.sign({ admin: data }, config.jwt.secret as string, {
    expiresIn: config.jwt.expire,
    // algorithm: 'RS256'
  });
}

function verify(token: string): {
  admin: JwtPayload | string | null,
  error: null | TokenExpiredError | JsonWebTokenError
} {
  try {
    return {
      admin: jwt.verify(token, config.jwt.secret as string),
      error: null,
    };
  } catch (error) {
    return {
      admin: null,
      error: error as null | TokenExpiredError | JsonWebTokenError,
    };
  }
}

export { sign, verify };
